import logging
import os


class logU:
    logger = None

    def __init__(self, cfg):
        cfgdir = os.path.split(os.path.realpath(__file__))[0]
        paths = cfgdir.split("/")
        a = len(paths) - 2 # 相当于 ../../命令
        separator = '/'
        arr = paths[1:a]
        b = '/' + separator.join(arr)+'/log'

        if cfg is None or cfg=='':
            cfg = b
        # 创建logger
        logU.logger = logging.getLogger('my_logger')
        logU.logger.setLevel(logging.DEBUG)  # 设置logger的level为DEBUG，这将影响所有的Handler

        # 创建fileHandler来输出错误到文件
        fh_error = logging.FileHandler(cfg+'/error.log')
        fh_error.setLevel(logging.ERROR)  # 设置fileHandler的level为ERROR

        # 创建fileHandler来输出警告及以上级别到文件
        fh_warning = logging.FileHandler(cfg+'/warning.log')
        fh_warning.setLevel(logging.WARNING)  # 设置fileHandler的level为WARNING

        # 创建fileHandler来输出警告及以上级别到文件
        fh_info = logging.FileHandler(cfg + '/info.log')
        fh_info.setLevel(logging.INFO)  # 设置fileHandler的level为WARNING

        # 创建streamHandler来输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)  # 设置streamHandler的level为DEBUG

        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh_error.setFormatter(formatter)
        fh_warning.setFormatter(formatter)
        ch.setFormatter(formatter)

        # 将Handler添加到logger
        logU.logger.addHandler(fh_error)
        logU.logger.addHandler(fh_warning)
        logU.logger.addHandler(ch)
        logU.logger.addHandler(fh_info)

    @staticmethod
    def get_logger(msg):
        logU.logger.error(msg)


if __name__ == "__main__":

    logU(cfg='').logger.info('my logger tools')